import Swiper from "swiper";
import React, { useEffect, useMemo, useRef, useState } from "react";
// import { SwiperSlide } from "swiper/react"; // 确保使用正确的swiper库
import axios from "../../utils/http"
import { useSelector, useDispatch } from "react-redux"
import { setActiveIndex } from "../../store/modules/yzh"
import VideoSlide from ".//VideoSlide"; // 视频模式

// 主页面
const Swipers = () => {
  // swiper属性
  const swiperColl = {
    direction: "vertical",
    autoplay: true,// 等同于以下设置
    // loop: true, // 循环模式选项
  }
  const dispatch = useDispatch()
  const [videoList, setVideoList] = useState([]) // 视频列表
  const swiperRef = useRef(null);  // 使用ref来引用swiper容器
  const containerRef = useRef(null) // 引用容器，用来监听滚动
  // const [activeIndex, setActiveIndex] = useState(0); // 当前活动视频索引
  const [currentPage, setCurrentPage] = useState(1); // 当前视频展示的页数
  const [totalPages, setTotalPages] = useState(1); // 视频总页数
  const [isLoading, setIsLoading] = useState(true)
  const swiperInstance = useRef(null); // Swiper实例引用
  const activeIndex = useSelector((store) => store.yzh.activeIndex) // 通过redux存储索引

  // 获取视频
  const getVideo = async () => {
    if (currentPage > totalPages) {
      console.log("没有视频啦！");
      return;
    }
    setIsLoading(true); // 开始加载
    try {
      const data = await axios.get("/yzh/getVideo", {
        params: {
          page: currentPage,
        },
      });
      if (data.code === 200) {
        setVideoList((prevVideoList) => [...prevVideoList, ...data.videoList]);
        setCurrentPage(currentPage + 1);
        setTotalPages(data.totalPages);
      }
    } catch (e) {
      console.error("获取视频失败:", e);
    } finally {
      setIsLoading(false); // 加载结束
    }
  };

  // 在活动视频索引接近最后一个时加载更多视频
  useMemo(() => {
    if (activeIndex === videoList.length - 1 && !isLoading) {
      // 如果滑动到倒数第二个视频，且没有在加载中，调用加载更多的视频
      getVideo();
    }
  }, [activeIndex, videoList, isLoading]);

  // 初始化 Swiper 实例
  useEffect(() => {
    // 如果没有视频或已经初始化过Swiper，就不需要重新实例化
    if (videoList.length > 0 && containerRef.current && !swiperInstance.current) {
      console.log("初始化执行，更新执行");
      console.log(videoList);

      // 初始化Swiper
      setTimeout(() => {
        swiperInstance.current = new Swiper(containerRef.current, {
          ...swiperColl,
          on: {
            slideChange: () => {
              dispatch(setActiveIndex(swiperInstance.current.activeIndex)) // 更新活动索引
              // console.log("当前滑动下标:", swiperInstance.current.activeIndex);
            },
          },
        });
      }, 200)
    } else if (swiperInstance.current) {
      // 当 videoList 更新时，强制更新 Swiper
      swiperInstance.current.update();
    }

    // 销毁 Swiper 实例
    // return () => {
    //   if (swiperInstance.current) {
    //     swiperInstance.current.destroy();
    //     swiperInstance.current = null;
    //   }
    // };
  }, [videoList]); // 只在 videoList 更新时初始化或销毁 Swiper

  useEffect(() => {
    getVideo(); // 初次加载时获取视频
  }, []); // 空依赖数组，表示只在组件加载时调用一次

  return (
    <>
      <div className="swiper contentFull" ref={containerRef}>
        <div className="swiper-wrapper" ref={swiperRef}>
          {
            videoList.length > 0 && videoList.map((item, index) => {
              return <VideoSlide
                key={item._id}
                item={item}
                index={index}
                activeIndex={activeIndex}
              />
            })
          }
        </div>
        {/* 如果需要分页器 */}
        {/* <div className="swiper-pagination"></div> */}
        {/* 如果需要导航按钮 */}
        {/* <div className="swiper-button-prev"></div>
                    <div className="swiper-button-next"></div> */}
        {/* 如果需要滚动条 */}
        {/* <div className="swiper-scrollbar"></div> */}
      </div>
    </>
  );
};


export default Swipers